#include "tcp.h"
#include "ui_tcp.h"

tcp::tcp(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::tcp)
{
    ui->setupUi(this);
    sock = new QTcpSocket(this);
    connect(sock, SIGNAL(connected()), this, SLOT(onConnected()));
    connect(sock, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
    connect(sock, SIGNAL(readyRead()), this, SLOT(onReceived()));
}

tcp::~tcp()
{
    delete ui;
}

void tcp::onConnected()
{
    ui->textBrowser->append(QString("%1 is connected").arg(ui->ipEdit->text()));
    ui->connectButton->setText("Disconnect");
}

void tcp::onDisconnected()
{
    ui->textBrowser->append(QString("%1 is disconnected").arg(ui->ipEdit->text()));
    ui->connectButton->setText("Connect");
}

void tcp::onReceived()
{
    QByteArray msg = sock->readAll();
    ui->textBrowser->append("> " + QString(msg).simplified());
}

void tcp::on_connectButton_clicked()
{
    QString host = ui->ipEdit->text();
    quint16 port = static_cast<quint16>(ui->portBox->value());
    if (sock->state() == QAbstractSocket::UnconnectedState)
    {
        sock->connectToHost(host, port);
    }
    else {
        sock->disconnectFromHost();
    }
}


void tcp::on_led_on_clicked()
{
    QString msg = "c";
    msg += "\r\n";
    sock->write(msg.toUtf8());
}

void tcp::on_led_off_clicked()
{
    QString msg = "f";
    msg += "\r\n";
    sock->write(msg.toUtf8());
}

void tcp::on_fan_on_clicked()
{
    QString msg = "b";
    msg += "\r\n";
    sock->write(msg.toUtf8());
}

void tcp::on_fan_off_clicked()
{
    QString msg = "e";
    msg += "\r\n";
    sock->write(msg.toUtf8());
}

void tcp::on_bee_on_clicked()
{
    QString msg = "a";
    msg += "\r\n";
    sock->write(msg.toUtf8());
}

void tcp::on_bee_off_clicked()
{
    QString msg = "d";
    msg += "\r\n";
    sock->write(msg.toUtf8());
}


